package cn.hg.solon.youcan.system.provider;

import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.system.entity.Dict;
import cn.hg.solon.youcan.system.entity.EqDict;
import cn.hg.solon.youcan.system.service.DictService;

/**
 * @author 胡高
 */
@Component
public class EqDictProvider implements DictService {

    @Db("db1")
    private EasyQuery easyQuery;

    private Queryable<EqDict> buildQuery(Map<String, Object> paraMap) {
        String type = (String)paraMap.get("type");
        String status = (String)paraMap.get("status");
        String word = (String)paraMap.get("word");
        String sortField = (String)paraMap.get("sortField");
        String sortType = (String)paraMap.get("sortType");

        boolean customOrder = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // FROM sys_dict AS t
        return this.easyQuery.queryable(EqDict.class)
            // WHERE t.`type` = ${type} AND t.`status` = ${status}
            //      AND (t.`name` LIKE '%${word}%' OR t.`type` LIKE '%${word}%')
            .where(w -> w.eq(StrValidator.isNotBlank(type), EqDict::getType, type)
                .eq(StrValidator.isNotBlank(status), EqDict::getStatus, status)
                .and(StrValidator.isNotBlank(word),
                    a -> a.like(EqDict::getName, word)
                    .or().like(EqDict::getType, word)))
            // ORDER BY ${sortField} DESC
            .orderBy(customOrder, ob -> ob.sqlNativeSegment(CharSequenceUtil.toUnderlineCase(sortField)),
                !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#checkUnique(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Override
    public boolean checkUnique(Dict bean) {
        return !this.easyQuery
            // FROM sys_dict AS t
            .queryable(EqDict.class)
            // WHERE t.`type` = ${bean.type}
            .where(w -> w.eq(EqDict::getType, bean.getType())
                // t.`value` = ${bean.value}
                .eq(EqDict::getName, bean.getName())
                // t.`id` <> ${bean.id}
                .ne(ObjUtil.isNotNull(bean.getId()), EqDict::getId, bean.getId()))
            .any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#delete(java.util.List)
     */
    @Tran
    @Override
    public boolean delete(List<Integer> idList) {
        return this.easyQuery.deletable(EqDict.class)
            .where(w -> w.in(EqDict::getId, idList))
            .executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#get(java.lang.Integer)
     */
    @Override
    public Dict get(Integer id) {
        return this.easyQuery.queryable(EqDict.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#getByType(java.lang.String)
     */
    @Override
    public Dict getByType(String type) {
        return this.easyQuery.queryable(EqDict.class).where(w -> w.eq(EqDict::getType, type)).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#insert(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Tran
    @Override
    public boolean insert(Dict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "字典名称已经存在，请更换其它值！");
        }

        EqDict cloneBean = BeanUtil.copyProperties(bean, EqDict.class);

        return this.easyQuery.insertable(cloneBean).executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#listByStatus(java.lang.String)
     */
    @Override
    public List<? extends Dict> listByStatus(String status) {
        // FROM sys_dict AS t
        return this.easyQuery.queryable(EqDict.class)
            // WHERE t.`status` = ${status}
            .where(w -> w.eq(EqDict::getStatus, status)).toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<? extends Dict> pageBy(int pageNumber, int pageSize, Map<String, Object> paraMap) {
        EasyPageResult<EqDict> pageList = this.buildQuery(paraMap).toPageResult(Convert.toLong(pageNumber), pageSize);

        PageResult<EqDict> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#update(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Tran
    @Override
    public boolean update(Dict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "字典名称已经存在，请更换其它值！");
        }

        EqDict cloneBean = (EqDict)this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyQuery.updatable(cloneBean).executeRows() > 0;
    }

}
